<template>
  <div class="salary-container">
    <el-card class="page-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <div class="header-left">
            <el-icon class="header-icon"><Money /></el-icon>
            <span class="header-title">{{ isHR ? '薪资管理' : '我的薪资' }}</span>
          </div>
          <div v-if="isHR" class="header-right">
            <el-button type="success" @click="exportData" :loading="exportLoading">
              <el-icon><Download /></el-icon>
              导出Excel
            </el-button>
            <el-button type="primary" @click="handleAddSalary">
              <el-icon><Plus /></el-icon>
              新增薪资
            </el-button>
          </div>
        </div>
      </template>
      
      <div v-if="salaryList.length === 0" class="empty-state">
        <el-empty description="暂无薪资记录" />
      </div>
      
      <el-table 
        v-else
        :data="salaryList" 
        style="width: 100%"
        stripe
        :empty-text="'暂无薪资记录'"
      >
        <el-table-column v-if="isHR" label="员工" width="150" align="center">
          <template #default="scope">
            <span>{{ scope.row.userName || `员工${scope.row.userId}` }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="month" label="月份" width="140" align="center">
          <template #default="scope">
            <span class="month-text">{{ scope.row.month }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="baseSalary" label="基本工资" width="140" align="right">
          <template #default="scope">
            <span class="salary-text">¥{{ formatMoney(scope.row.baseSalary) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="bonus" label="奖金" width="140" align="right">
          <template #default="scope">
            <span class="bonus-text">+¥{{ formatMoney(scope.row.bonus || 0) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="deduction" label="扣除" width="140" align="right">
          <template #default="scope">
            <span class="deduction-text">-¥{{ formatMoney(scope.row.deduction || 0) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="total" label="实发工资" width="160" align="right">
          <template #default="scope">
            <span class="total-text">¥{{ formatMoney(scope.row.total) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" align="center">
          <template #default="scope">
            <span class="time-text">{{ formatDate(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column v-if="isHR" label="操作" width="120" align="center" fixed="right">
          <template #default="scope">
            <el-button 
              type="primary" 
              link 
              size="small"
              @click="handleEditSalary(scope.row)"
            >
              编辑
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div v-if="salaryList.length > 0" class="summary-section">
        <el-card class="summary-card" shadow="never">
          <div class="summary-content">
            <div class="summary-item">
              <span class="summary-label">总记录数：</span>
              <span class="summary-value">{{ salaryList.length }}条</span>
            </div>
            <div class="summary-item">
              <span class="summary-label">平均月薪：</span>
              <span class="summary-value highlight">¥{{ formatMoney(avgSalary) }}</span>
            </div>
            <div class="summary-item">
              <span class="summary-label">累计收入：</span>
              <span class="summary-value highlight">¥{{ formatMoney(totalSalary) }}</span>
            </div>
          </div>
        </el-card>
      </div>
    </el-card>
    
    <!-- 编辑/新增薪资弹窗 -->
    <el-dialog
      v-model="salaryDialogVisible"
      :title="isEdit ? '编辑薪资' : '新增薪资'"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="salaryFormRef"
        :model="salaryForm"
        :rules="salaryRules"
        label-width="120px"
      >
        <el-form-item v-if="!isEdit" label="员工" prop="userId">
          <el-select
            v-model="salaryForm.userId"
            placeholder="请选择员工"
            filterable
            style="width: 100%"
            :loading="userListLoading"
          >
            <el-option
              v-for="user in userList"
              :key="user.id"
              :label="`${user.name || user.username} (${user.username})`"
              :value="user.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item v-else label="员工">
          <el-input :value="currentEmployeeName" disabled />
        </el-form-item>
        <el-form-item label="月份" prop="month">
          <el-date-picker
            v-model="salaryForm.month"
            type="month"
            placeholder="选择月份"
            format="YYYY-MM"
            value-format="YYYY-MM"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="基本工资" prop="baseSalary">
          <el-input-number
            v-model="salaryForm.baseSalary"
            :min="0"
            :precision="2"
            :step="100"
            style="width: 100%"
            placeholder="请输入基本工资"
          />
        </el-form-item>
        <el-form-item label="奖金" prop="bonus">
          <el-input-number
            v-model="salaryForm.bonus"
            :min="0"
            :precision="2"
            :step="100"
            style="width: 100%"
            placeholder="请输入奖金"
          />
        </el-form-item>
        <el-form-item label="扣除" prop="deduction">
          <el-input-number
            v-model="salaryForm.deduction"
            :min="0"
            :precision="2"
            :step="100"
            style="width: 100%"
            placeholder="请输入扣除金额"
          />
        </el-form-item>
        <el-form-item label="实发工资">
          <el-input
            :value="formatMoney(calculatedTotal)"
            disabled
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="salaryDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSaveSalary" :loading="saveLoading">
            保存
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, onMounted, computed } from 'vue'
import request from '../utils/request'
import { ElMessage } from 'element-plus'
import { Money, Plus, Download } from '@element-plus/icons-vue'

export default {
  name: 'Salary',
  components: {
    Money,
    Plus,
    Download
  },
  setup() {
    const salaryList = ref([])
    const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
    const isHR = computed(() => userInfo.role === 'HR')
    const salaryDialogVisible = ref(false)
    const salaryFormRef = ref(null)
    const saveLoading = ref(false)
    const isEdit = ref(false)
    const currentSalary = ref(null)
    const userList = ref([])
    const userListLoading = ref(false)
    const exportLoading = ref(false)
    
    const salaryForm = ref({
      userId: null,
      month: '',
      baseSalary: 0,
      bonus: 0,
      deduction: 0
    })
    
    const formatDate = (dateStr) => {
      if (!dateStr) return ''
      return new Date(dateStr).toLocaleString('zh-CN')
    }
    
    const formatMoney = (amount) => {
      if (amount === null || amount === undefined) return '0.00'
      const num = Number(amount)
      if (isNaN(num)) return '0.00'
      return num.toLocaleString('zh-CN', {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2
      })
    }
    
    // 表单验证规则
    const salaryRules = {
      userId: [
        { required: true, message: '请选择员工', trigger: 'change' }
      ],
      month: [
        { required: true, message: '请选择月份', trigger: 'change' }
      ],
      baseSalary: [
        { required: true, message: '请输入基本工资', trigger: 'blur' },
        { type: 'number', min: 0, message: '基本工资不能为负数', trigger: 'blur' }
      ],
      bonus: [
        { type: 'number', min: 0, message: '奖金不能为负数', trigger: 'blur' }
      ],
      deduction: [
        { type: 'number', min: 0, message: '扣除不能为负数', trigger: 'blur' }
      ]
    }
    
    // 计算实发工资
    const calculatedTotal = computed(() => {
      const base = Number(salaryForm.value.baseSalary) || 0
      const bonus = Number(salaryForm.value.bonus) || 0
      const deduction = Number(salaryForm.value.deduction) || 0
      const total = base + bonus - deduction
      return Math.max(0, total) // 确保不为负数
    })
    
    // 当前员工名称（编辑时显示）
    const currentEmployeeName = computed(() => {
      if (!currentSalary.value) return ''
      return currentSalary.value.userName || `员工${currentSalary.value.userId}`
    })
    
    // 加载用户列表（用于新增时选择员工）
    const loadUserList = async () => {
      if (userList.value.length > 0) return // 已加载过
      try {
        userListLoading.value = true
        const res = await request.get('/user/list')
        if (res.code === 200 && res.data) {
          userList.value = res.data
        }
      } catch (error) {
        ElMessage.error('加载用户列表失败')
      } finally {
        userListLoading.value = false
      }
    }
    
    // 打开编辑弹窗
    const handleEditSalary = (row) => {
      isEdit.value = true
      currentSalary.value = row
      salaryForm.value = {
        userId: row.userId,
        month: row.month,
        baseSalary: Number(row.baseSalary) || 0,
        bonus: Number(row.bonus) || 0,
        deduction: Number(row.deduction) || 0
      }
      salaryDialogVisible.value = true
    }
    
    // 打开新增弹窗
    const handleAddSalary = async () => {
      isEdit.value = false
      currentSalary.value = null
      salaryForm.value = {
        userId: null,
        month: '',
        baseSalary: 0,
        bonus: 0,
        deduction: 0
      }
      await loadUserList()
      salaryDialogVisible.value = true
    }
    
    // 保存薪资（新增或更新）
    const handleSaveSalary = async () => {
      if (!salaryFormRef.value) return
      
      try {
        await salaryFormRef.value.validate()
        saveLoading.value = true
        
        const data = {
          userId: salaryForm.value.userId,
          month: salaryForm.value.month,
          baseSalary: salaryForm.value.baseSalary,
          bonus: salaryForm.value.bonus || 0,
          deduction: salaryForm.value.deduction || 0
        }
        
        let res
        if (isEdit.value) {
          // 更新
          res = await request.put(`/salary/update/${currentSalary.value.id}`, data)
        } else {
          // 新增
          res = await request.post('/salary/create', data)
        }
        
        if (res.code === 200) {
          ElMessage.success(isEdit.value ? '更新成功' : '创建成功')
          salaryDialogVisible.value = false
          loadSalaryList() // 重新加载列表
        } else {
          ElMessage.error(res.message || '操作失败')
        }
      } catch (error) {
        if (error.response && error.response.data && error.response.data.message) {
          ElMessage.error(error.response.data.message)
        } else {
          ElMessage.error('操作失败')
        }
      } finally {
        saveLoading.value = false
      }
    }
    
    const avgSalary = computed(() => {
      if (salaryList.value.length === 0) return 0
      const sum = salaryList.value.reduce((acc, item) => {
        const total = Number(item.total) || 0
        return acc + total
      }, 0)
      return sum / salaryList.value.length
    })
    
    const totalSalary = computed(() => {
      return salaryList.value.reduce((acc, item) => {
        const total = Number(item.total) || 0
        return acc + total
      }, 0)
    })
    
    const loadSalaryList = async () => {
      try {
        // HR角色查看所有薪资，员工角色查看自己的薪资
        const apiPath = isHR.value ? '/salary/all' : '/salary/my'
        const res = await request.get(apiPath)
        salaryList.value = res.data || []
      } catch (error) {
        ElMessage.error('加载薪资记录失败')
      }
    }
    
    // 导出数据
    const exportData = async () => {
      exportLoading.value = true
      try {
        const token = localStorage.getItem('token')
        const url = '/api/salary/export'
        
        const response = await fetch(url, {
          method: 'GET',
          headers: {
            'Authorization': `Bearer ${token}`
          }
        })
        
        if (!response.ok) {
          throw new Error('导出失败')
        }
        
        const blob = await response.blob()
        const downloadUrl = window.URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.href = downloadUrl
        link.download = `薪资记录_${new Date().toISOString().slice(0, 7)}.xlsx`
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        window.URL.revokeObjectURL(downloadUrl)
        
        ElMessage.success('导出成功')
      } catch (error) {
        ElMessage.error('导出失败：' + (error.message || '未知错误'))
      } finally {
        exportLoading.value = false
      }
    }
    
    onMounted(() => {
      loadSalaryList()
    })
    
    return {
      salaryList,
      isHR,
      formatDate,
      formatMoney,
      avgSalary,
      totalSalary,
      salaryDialogVisible,
      salaryForm,
      salaryFormRef,
      salaryRules,
      saveLoading,
      isEdit,
      currentSalary,
      userList,
      userListLoading,
      calculatedTotal,
      currentEmployeeName,
      handleEditSalary,
      handleAddSalary,
      handleSaveSalary,
      exportLoading,
      exportData
    }
  }
}
</script>

<style scoped>
.salary-container {
  width: 100%;
  height: 100%;
}

.page-card {
  border-radius: 12px;
  border: none;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.header-icon {
  font-size: 24px;
  color: #409eff;
}

.header-title {
  font-size: 20px;
  font-weight: 600;
  color: #1a1a1a;
}

.empty-state {
  padding: 60px 0;
}

.month-text {
  font-weight: 500;
  color: #333;
}

.salary-text {
  color: #666;
  font-size: 14px;
}

.bonus-text {
  color: #67c23a;
  font-weight: 500;
}

.deduction-text {
  color: #f56c6c;
  font-weight: 500;
}

.total-text {
  color: #409eff;
  font-size: 18px;
  font-weight: 700;
}

.time-text {
  color: #8c8c8c;
  font-size: 14px;
}

.summary-section {
  margin-top: 32px;
}

.summary-card {
  background: #f5f7fa;
  border: 1px solid #e4e7ed;
  border-radius: 12px;
}

.summary-content {
  display: flex;
  justify-content: space-around;
  align-items: center;
  padding: 20px 0;
}

.summary-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
}

.summary-label {
  font-size: 14px;
  color: #666;
}

.summary-value {
  font-size: 24px;
  font-weight: 600;
  color: #333;
}

.summary-value.highlight {
  color: #409eff;
  font-size: 28px;
}

:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-table th) {
  background-color: #fafafa;
  color: #333;
  font-weight: 600;
}

:deep(.el-table td) {
  padding: 16px 0;
}
</style>

